<template>
  <span>
    <common-dialog
      title="导入"
      :visible="isUploadDialog"
      width="400px"
      @close="closeUploadDialog"
    >
      <div slot="default" class="global-common-upload-dialog-body">
        <el-upload
          ref="upload"
          :limit="1"
          :accept="acceptType"
          :headers="upload.headers"
          :action="uploadActon"
          :data="uploadData"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-change="handleFileUploadChange"
          :before-upload="beforeFileUpload"
          :on-success="handleFileSuccess"
          :auto-upload="false"
          :show-file-list="false"
          drag
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">
            将文件拖到此处，或
            <em>点击上传</em>
          </div>
          <div
            class="el-upload__tip"
            slot="tip"
            v-if="acceptType !== '.txt' && acceptType !== '.lic'"
          >
            <el-link
              type="primary"
              style="font-size: 12px"
              @click="downloadTemplate"
              >下载模板</el-link
            >
          </div>
          <div class="el-upload__tip" style="color: red" slot="tip">
            提示仅允许导入<span>{{ acceptType }}</span
            >格式文件！文件大小小于10MB
          </div>
          <ul
            class="el-upload-list el-upload-list--text"
            slot="tip"
            v-if="fileName"
          >
            <li tabindex="0" class="el-upload-list__item is-ready">
              <a
                class="el-upload-list__item-name"
                style="display: flex; line-height: 20px"
              >
                <i class="el-icon-document"></i>
                <common-carousel-text :content="fileName" :font-size="14">
                </common-carousel-text>
              </a>
              <i class="el-icon-close" @click="handleFileDelent"></i>
            </li>
          </ul>
        </el-upload>
      </div>
      <div slot="footer">
        <el-button @click="closeUploadDialog">取 消</el-button>
        <el-button
          type="primary"
          @click="submitFileForm"
          :loading="upload.isUploading"
          >确 定</el-button
        >
      </div>
    </common-dialog>
    <common-dialog
      title="导入结果"
      :visible="isResultDialog"
      width="400px"
      top="40vh"
      @submit="downloadErrorReport"
      @close="closeResultDialog"
    >
      <div slot="default" class="global-common-upload-dialog-body">
        <div>{{ result.message }}</div>
        <div v-if="result.isDownload">
          <el-button type="text" @click="downloadErrorReport"
            >下载错误报告</el-button
          >
        </div>
      </div>
      <div slot="footer">
        <el-button type="primary" @click="closeResultDialog">确 定</el-button>
      </div>
    </common-dialog>
  </span>
</template>

<script>
import CommonDialog from "@/components/CommonDialog";
import { getTokenDecrypt } from "@/utils/auth";

export default {
  name: "CommonUploadDialog",
  props: {
    uploadPath: {
      type: String,
      default: "", // /system/user/importData
    },
    uploadData: {
      type: Object,
      default: () => ({}),
    }, // 上传附带参数
    downloadPath: {
      type: String,
      default: "", // system/downFileByemplateName
    },
    reportPath: {
      type: String,
      default: "", // system/downErrorReportByemplateName
    },
    templateName: {
      type: String,
      default: "template.xls",
    },
    getList: {
      type: Function,
    },
    acceptType: {
      type: String,
      default: ".xlsx, .xls",
    },
  },
  data() {
    return {
      isUploadDialog: false,
      isResultDialog: false,
      result: {
        message: "",
        fileName: "",
        isDownload: false,
      },
      fileName: "",
      // 用户导入参数
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getTokenDecrypt() },
      },
    };
  },
  components: {
    CommonDialog,
  },
  computed: {
    uploadActon: function () {
      let domain = process.env.VUE_APP_BASE_API;
      return `${domain}${this.uploadPath}?updateSupport=${this.upload.updateSupport}`;
    },
  },
  methods: {
    //删除
    handleFileDelent() {
      this.$refs.upload.uploadFiles = [];
      this.fileName = null;
    },
    // 文件状态改变时触发
    handleFileUploadChange(file) {
      this.fileName = file.name.substring(0, file.name.lastIndexOf("."));
    },
    /**
     * 下载模板文件
     */
    downloadTemplate() {
      this.download(
        this.downloadPath,
        { templateName: this.templateName },
        this.templateName
      );
    },

    beforeFileUpload(file) {
      const maxSize = 10 * 1024 * 1024; // Bytes
      let fileName = file.name.substring(0, file.name.lastIndexOf("."));
      let fileType = file.name.substring(file.name.lastIndexOf(".") + 1);
      // console.log('文件后缀: ', fileType)

      if (this.acceptType.includes(fileType)) {
        if (file.size > maxSize) {
          this.$GlobalErrorConfirm("上传失败", "文件大小超出限制!最大10MB");
          return false;
        } else {
          return true;
        }
      } else {
        this.$GlobalErrorConfirm(
          "上传失败",
          `文件类型错误!仅允许导入${this.acceptType}文件`
        );
        return false;
      }
    },
    /**
     * 文件上传中
     * @param event
     * @param file
     * @param fileList
     */
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    /**
     * 文件上传完成回调
     * @param res
     * @param file
     * @param fileList
     */
    handleFileSuccess(res, file, fileList) {
      this.upload.isUploading = false;
      this.closeUploadDialog();

      if (res) {
        if (res.code === 200) {
          this.$nextTick(() => {
            this.result.isDownload = res.msg.indexOf("成功") === -1;
            let resultArray = res.msg.split("<br/>");
            if (this.result.isDownload) {
              this.result.message = resultArray[0];
              this.result.fileName = resultArray[1];
            } else {
              this.result.message = res.msg;
            }
            if (this.getList && typeof this.getList === "function") {
              this.getList();
            }
            this.isResultDialog = true;
          });
        } else {
          this.$GlobalErrorConfirm("上传失败", res.msg);
        }
      } else {
        this.$GlobalErrorConfirm("上传失败", "未知异常");
      }
    },
    /**
     * 提交上传文件
     */
    submitFileForm() {
      if (!this.fileName)
        return this.$GlobalErrorConfirm("导入失败", "请选择要上传的文件");
      this.$refs.upload.submit();
    },
    /**
     * 关闭文件上传弹框
     */
    closeUploadDialog() {
      this.$refs.upload.clearFiles();
      this.isUploadDialog = false;
    },
    /**
     * 显示文件上传弹框
     */
    show() {
      this.isUploadDialog = true;
      this.fileName = null;
    },
    /**
     * 下载错误报告
     */
    downloadErrorReport() {
      // console.log("this.result", this.result);
      if (this.result.isDownload && this.result.fileName) {
        this.download(
          this.reportPath,
          { fileName: this.result.fileName },
          this.result.fileName
        );
      }
      this.closeResultDialog();
    },
    closeResultDialog() {
      this.isResultDialog = false;
      if (!this.result.isDownload) {
        this.$emit("closeResultDialog");
      }
    },
  },
  mounted() {},
};
</script>

<style scoped lang="scss">
.global-common-upload-dialog-body {
  padding: 12px 18px;
  box-sizing: border-box;
  border-bottom: 1px solid #eee;
}
</style>
